package com.example.apiinterfacesdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.example.apiinterfacesdk.model.User;


import java.util.HashMap;

import static com.example.apiinterfacesdk.utils.SignUtils.genSign;


public class ApiClient {


    private String accessKey;
    private String secretKey;

    public static final String GETWETD_HOST="http://localhost:8090/api/name";

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getUserByGet(String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name",name);
        return HttpUtil.get(GETWETD_HOST+"/get/?",hashMap);
    }


    public String getUserByPost(  String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name",name);
        return HttpUtil.post(GETWETD_HOST+"/post/?",hashMap);
    }

    /**
     * 生成请求头，以便接口获取数据
     * @param body
     * @return
     */
    public HashMap<String,String > getHeaders(String body){
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey",accessKey);
//        hashMap.put("secretKey",secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body",body);
        hashMap.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        hashMap.put("sign", genSign(body,secretKey));

        return hashMap;
    }


    public String getUserNameByPost(User user) {
        String jsonStr = JSONUtil.toJsonStr(user);
        HttpResponse execute = HttpRequest.post(GETWETD_HOST+"/user/?" + jsonStr)
                .addHeaders(getHeaders(jsonStr))
                .body(jsonStr)
                .execute();

        System.out.println(execute.getStatus());
        String body = execute.body();
        System.out.println(body);
        return body;
    }
}
